<template>
  <VTable ref="tableRef" v-bind="tableOptins">
    <template #form="{ form }">
      <VSelects
        v-model="form.type"
        :dataSourse="optionsDataAll?.fund_dispatch_type || []"
        placeholder="类型"
        clearable
      />
      <!-- <VGroup>
        <VSelects v-model="form.state" :dataSourse="[]" class="w-[100px]" />
        <VSelects
          v-model="form.state"
          :dataSourse="[]"
          placeholder="账号/卡号"
          clearable
        />
      </VGroup>
      <VGroup>
        <VSelects v-model="form.state" :dataSourse="[]" class="w-[100px]" />
        <VSelects
          v-model="form.state"
          :dataSourse="[]"
          placeholder="账号/卡号"
          clearable
        />
      </VGroup> -->
      <VGroup>
        <VSelects
          v-model="form.moneyType.type"
          :dataSourse="othersData.moneyType"
          class="w-[100px]"
        />
        <rangeInput v-model="form.moneyType.value" class="w-[200px]" />
      </VGroup>
      <VGroup>
        <VSelects
          v-model="form.currencyType.type"
          :dataSourse="othersData.currencyType"
          class="w-[100px]"
        />
        <VSelects
          v-model="form.currencyType.value"
          :dataSourse="optionsDataAll?.currency || []"
          placeholder="请选择"
          valueField="label"
          clearable
          multiple
          collapse-tags
          collapse-tags-tooltip
        />
      </VGroup>
      <VGroup>
        <VSelects
          v-model="form.createAuditTime.type"
          :dataSourse="othersData.createAuditTime"
          class="w-[100px]"
        />
        <rangeTime v-model="form.createAuditTime.value" />
      </VGroup>
      <VGroup>
        <VSelects
          v-model="form.user.type"
          :dataSourse="othersData.personnel"
          class="w-[100px]"
        />
        <VCascader
          v-model="form.user.value"
          collapse-tags
          style="width: 200px"
        />
      </VGroup>
    </template>
    <template #toolbar_btns>
      <VActionBar :actions="actions" />
    </template>
  </VTable>
  <Add
    v-model="addVisible"
    :title="addTitle"
    :data="addData"
    @refresh="refresh"
    @close="addData = null"
    :optionsData="optionsDataAll"
  />
  <VAudit
    v-model="auditVisible"
    title="审核"
    :option="[
      { label: '已审核', value: 1 },
      { label: '审核失败', value: 2 },
    ]"
    url="/fundDispatch/review"
    :isRemark="false"
    :ids="auditId"
    @close="auditId = null"
    @refresh="refresh"
  />
  <DerivedCenter ref="DerivedCenterRef"></DerivedCenter>
</template>
<script setup lang="jsx">
import { ElMessage } from "element-plus";
import { getTableSelectRow } from "@/hooks/tools.js";
import { config_name } from "@/config/export.js";
import othersData from "@/data/search.js";
import rangeInput from "@/components/rangeInput/index.vue";
import { useEnumSelect } from "@/hooks/index.js";
import { getCurrency } from "@/api/index.js";
import tagStatus from "@/components/tagStatus/index.vue";
import { getCapitalDispatchList, deleteCapitalDispatch } from "../../api.js";
import Add from "./add/index.vue";
import rangeTime from "@/components/rangeTime/index.vue";
import { getChannelList } from "@/api/index.js";
import { transformData } from "@/utils/tools.js";
import { capitalAuthList } from "@/Auth/capital.js";
const { options: optionsData } = useEnumSelect({
  /**
   * fund_dispatch_type:类型
   * account_type:支出账号类型
   *
   */
  params: ["fund_dispatch_type", "account_type"],
});
const tableRef = ref();
//获取币种
const optionsData1 = ref({});
const currency = async () => {
  const { data } = await getCurrency();
  optionsData1.value.currency = data;
};
currency();
const optionsDataAll = computed(() => {
  return {
    ...optionsData.value,
    ...optionsData1.value,
  };
});
const tableOptins = reactive({
  formConfig: {
    data: {
      type: "",
      state: "",
      moneyType: {
        type: "expenditureAmount",
        value: [],
      },
      currencyType: {
        type: "expenditureCurrency",
        value: "",
      },
      createAuditTime: {
        type: "createdAt",
        value: [],
      },
      user: {
        type: "createUser",
        value: "",
      },
    },
  },
  tooltipConfig: {
    showAll: false,
  },
  isToggle: true,
  columns: [
    {
      type: "checkbox",
      width: 50,
      fixed: "left",
    },
    {
      title: "ID",
      field: "id",
      fixed: "left",
      width: 200,
      slots: {
        default: ({ row }) => {
          return <span>{row?.id?.toString()}</span>;
        },
      },
    },
    {
      title: "类型",
      fixed: "left",
      field: "type",
      minWidth: 100,
      slots: {
        default: ({ row }) => {
          return <span>{row.type.label}</span>;
        },
      },
    },
    {
      title: "状态",
      field: "state",
      minWidth: 100,
      slots: {
        default: ({ row }) => {
          return (
            <tagStatus
              code={row?.state}
              type={[
                { label: 0, value: "warning" },
                { label: 1, value: "primary" },
                { label: 2, value: "danger" },
              ]}
            />
          );
        },
      },
    },
    {
      title: "支出渠道",
      field: "expenditureChannelDescribe",
      width: 100,
    },
    {
      title: "账号/卡号",
      field: "expenditureAccount",
      width: 150,
    },
    {
      title: "支出币种",
      field: "expenditureCurrency",
      width: 100,
    },
    {
      title: "支出金额",
      field: "expenditureAmount",
      width: 150,
    },
    {
      title: "收入渠道",
      field: "incomeChannelDescribe",
      width: 150,
    },
    {
      title: "账号/卡号",
      field: "incomeAccount",
      width: 100,
    },
    {
      title: "收入币种",
      field: "incomeCurrency",
      width: 100,
    },
    {
      title: "收入金额",
      field: "incomeAmount",
      width: 150,
    },
    {
      title: "汇率",
      field: "exchangeRate",
      width: 100,
    },
    {
      title: "备注信息",
      field: "remark",
      width: 200,
    },
    {
      title: "添加时间",
      field: "createdAt",
      width: 170,
    },
    {
      title: "添加人员",
      field: "createUser",
      width: 170,
    },
    {
      title: "审核时间",
      field: "reviewAt",
      width: 170,
    },
    {
      title: "审核人员",
      field: "reviewUser",
      width: 170,
    },
    {
      title: "操作",
      width: 145,
      fixed: "right",
      slots: {
        default: ({ row }) => {
          return (
            <div>
              {[capitalAuthList.dispatch.fund_procurement.edit] &&
                row.state.value != 1 && (
                  <el-button type="primary" link onClick={() => handleAdd(row)}>
                    编辑
                  </el-button>
                )}
              {[capitalAuthList.dispatch.fund_procurement.edit] && (
                <el-button type="primary" link>
                  日志
                </el-button>
              )}
              {[capitalAuthList.dispatch.fund_procurement.delete] &&
                row.state.value != 1 && (
                  <el-button
                    type="danger"
                    link
                    onClick={() => handleDelete(row.id)}
                  >
                    删除
                  </el-button>
                )}
            </div>
          );
        },
      },
    },
  ],
  proxyConfig: {
    props: {
      result: "data",
      total: "total",
    },
    autoLoad: false,
    ajax: {
      query: ({ page, form }) => {
        let params = transformData(form);
        const { expenditureAmount, incomeAmount } = params;
        params = {
          ...params,
          expenditureAmountMin: expenditureAmount?.min,
          expenditureAmountMax:
            expenditureAmount?.max == 0 ? undefined : expenditureAmount?.max,
          expenditureAmount: undefined,
          incomeAmountMin: incomeAmount?.min,
          incomeAmountMax: incomeAmount?.max,
          incomeAmount: undefined,
        };
        return getCapitalDispatchList({ ...params, ...page }).then((res) => {
          return {
            data: res.data,
            total: res.total,
          };
        });
      },
    },
  },
});
const getChannel = async () => {
  const { data } = await getChannelList({
    pageNum: 1,
    pageSize: 100,
  });
  optionsData1.value.channelList = data || [];
};
getChannel();
//导出中心
const DerivedCenterRef = ref();
const handleExport = async () => {
  let condition = getTableSelectRow(tableRef.value);
  DerivedCenterRef.value.open({
    tag_name: config_name["capital"]["fund_dispatch"],
    condition,
  });
};
const actions = [
  {
    label: "新增",
    type: "primary",
    icon: "add1",
    fn: () => handleAdd(null),
    permission: [capitalAuthList.dispatch.fund_procurement.add],
  },
  {
    label: "审核",
    type: "primary",
    fn: () => handleAudit(),
    permission: [capitalAuthList.dispatch.fund_procurement.audit],
  },
  {
    label: "导入",
    dkicon: "icon-Download",
    right: true,
    fn: () => handleImport(),
    permission: [capitalAuthList.dispatch.fund_procurement.import],
  },
  {
    label: "导出",
    right: true,
    dkicon: "icon-Upload",
    fn: handleExport,
    permission: [capitalAuthList.dispatch.fund_procurement.export],
  },
];

const handleDelete = (id) => {
  proxy?.confirm({
    title: "提示",
    content: (
      <p>
        确认删除
        <span class="text-[#3366F1] px-[4px]">{1}</span>
        条数据？
      </p>
    ),
    beforeClose: async (action, instance, done) => {
      if (action === "confirm") {
        try {
          instance.confirmButtonLoading = true;
          instance.confirmButtonText = "处理中..";
          const { code, message } = await deleteCapitalDispatch({ id });
          if (code !== 200) return ElMessage.success(message);
          ElMessage.success("删除成功!");
        } catch (e) {
          console.error(e);
        } finally {
          instance.confirmButtonLoading = false;
          done();
          refresh();
        }
      } else {
        done();
      }
    },
  });
};
const addVisible = ref(false);
const addData = ref(null);
const addTitle = ref("新增");
const handleAdd = (row) => {
  addVisible.value = true;
  let data = null;
  if (row?.id) {
    data = {
      ...row,
      type: row?.type?.value,
      expenditureAccountType: row?.expenditureAccountType?.value,
      expenditureChannel: row?.expenditureChannel?.toString(),
      expenditureAccountId: row?.expenditureAccountId?.toString(),
      incomeAccountType: row?.incomeAccountType?.value,
      incomeChannel: row?.incomeChannel?.toString(),
      incomeAccountId: row?.incomeAccountId?.toString(),
    };
  }
  addData.value = data || null;
  addTitle.value = data?.id ? "编辑" : "新增";
};
//审核
const auditVisible = ref(false);
const auditId = ref(null);
const handleAudit = (row) => {
  let records = tableRef.value?.$table.getCheckboxRecords();
  if (!records?.length) return ElMessage.warning("请至少选择一条数据!");
  //判断state是否含有审核成功
  const isReview = records.some((item) => item.state.value === 1);
  if (isReview) return ElMessage.warning("审核通过的数据不能再审核!");
  const ids = records.map((item) => item.id);
  auditId.value = ids;
  auditVisible.value = true;
};
const refresh = () => {
  tableRef?.value.$table.commitProxy("query");
};
</script>
<style lang="scss" scoped>
.vx-table {
  height: calc(100% - 40px) !important;
}
:deep(.el-tag.el-tag--danger){
  background-color: var(--base-danger-bg)
}
:deep(.el-tag.el-tag--primary){
  background-color: var(--base-primary-bg);
  border-color: var(--base-primary-bg);;
}
:deep(.el-tag.el-tag--warning){
  background-color: var(--base-warning-bg);
  border-color: var(--base-warning-bg);;
}
</style>
